<?php

namespace App\Console\Commands\Elasticsearch;

use App\Models\Example;
use Illuminate\Console\Command;

class TestElasticsearch extends Command
{

    protected $signature = 'es:test';


    protected $description = 'ES 搜索同步数据测试';


    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 创建索引: curl -XPUT http://localhost:9200/example
     * 添加类型: curl -H'Content-Type: application/json' -XPUT http://localhost:9200/example/_mapping?pretty -d'{
                    "properties": {
                        "title": { "type": "text"}
                    }
                }'
     */
    public function handle()
    {
        $es = app('es');

        Example::query()
            ->chunkById(100,function ($examples) use ($es){
                $this->info(sprintf('正在同步 ID 范围为 %s 至 %s 的商数据', $examples->first()->id, $examples->last()->id));

                $req = [];
                foreach ($examples as $example) {
                    $data = $example->toESArray();

                    // 一个一个添加
//                    app('es')->index([
//                        'id'    => $data['id'],
//                        'index' => 'example',
//                        'type' => '_doc',
//                        'body'  => $data,
//                    ]);

                    $req['body'][] = [
                        'index' => [
                            '_index' => 'example',
                            '_id'    => $data['id'],
                        ],
                    ];
                    $req['body'][] = $data;
                }

                try {
                    // 使用 bulk 方法批量创建
                    $es->bulk($req);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
            });
        $this->info('同步完成');
    }
}
